package com.weiyi.mashangzhu.Landlord.Activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.Landlord.Adapter.DiscountAdapter;
import com.weiyi.mashangzhu.Landlord.Adapter.NextAdapter;
import com.weiyi.mashangzhu.Landlord.Bean.DiscountBean;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Activity.ShareActivity;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.Weight.WheelView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BaseInfoActivity extends BaseActivity {

    @BindView(R.id.lv)
    ListView lv;
    List<DiscountBean> list = new ArrayList<>();
    WheelView wv_shi, wv_ting, wv_wei, wv_chu;
    private static final String[] SHI = new String[99];
    private static final String[] TING = new String[100];
    private static final String[] WEI = new String[100];
    private static final String[] CHU = new String[100];
    TextView affirm;
    DiscountAdapter discountAdapter = null;
    WheelView wva;
    private static final String[] PLANETS = new String[99];
    String info;
    String id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_info);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        info = intent.getStringExtra("info");
        id = intent.getStringExtra("id");
        for (int i = 1; i < PLANETS.length + 1; i++) {
            PLANETS[i - 1] = i + "人";
        }
        for (int i = 0; i < SHI.length; i++) {
            SHI[i] = (i + 1) + "室";
        }
        for (int i = 0; i < TING.length; i++) {
            TING[i] = i + "厅";
            WEI[i] = i + "卫";
            CHU[i] = i + "厨";
        }
        list.add(new DiscountBean("房间面积", ""));
        list.add(new DiscountBean("户型", ""));
        list.add(new DiscountBean("卫生间", ""));
        list.add(new DiscountBean("可住人数", ""));
        list.add(new DiscountBean("床铺信息", ""));
        discountAdapter = new DiscountAdapter(list, this);
        lv.setAdapter(discountAdapter);
        if (info.equals("post")) {
            //上传房源
            if (MyApp.base_area != null) {
                list.get(0).setCount(MyApp.base_area + "平方");
                discountAdapter.notifyDataSetChanged();
            }
            if (MyApp.base_type != null) {
                list.get(1).setCount(MyApp.base_type);
                discountAdapter.notifyDataSetChanged();
            }
            if (MyApp.base_wei != null) {
                String s = "";
                if (MyApp.base_wei.equals("0")) {
                    s = "独立卫生间";
                } else if (MyApp.base_wei.equals("1")) {
                    s = "共用卫生间";
                }
                list.get(2).setCount(s);
                discountAdapter.notifyDataSetChanged();
            }
            if (MyApp.base_person != null) {
                list.get(3).setCount(MyApp.base_person + "人");
                discountAdapter.notifyDataSetChanged();
            }
        } else {
            //修改房源
            LoadingDialog.show(this);
            OkHttpUtils.get()
                    .addParams("token", SPUtils.get(this, "token", "") + "")
                    .addParams("id", id)
                    .url(API.BaseApi_L + API.GetHouseBaseInfo_Api)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {
                            LoadingDialog.dismiss(BaseInfoActivity.this);
                            T.showShort(BaseInfoActivity.this, "网络连接失败");

                        }

                        @Override
                        public void onResponse(String response) {
                            LoadingDialog.dismiss(BaseInfoActivity.this);
                            Log.e("bbbbbbbbbb", "re=" + response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getInt("status") == 0) {
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                                    MyApp.re_bedtype = jsonObject1.getString("hBedtype");
                                    MyApp.re_bedl = jsonObject1.getDouble("hBedlength")+"";
                                    MyApp.re_bedw = jsonObject1.getDouble("hBedwidth")+"";
                                    MyApp.re_bedcount = jsonObject1.getString("hBednum");
                                    list.get(0).setCount(jsonObject1.getString("hArea") + "平方");
                                    list.get(1).setCount(jsonObject1.getInt("hRoom") + "室" + jsonObject1.getInt("hHall") + "厅" + jsonObject1.getInt("hRooms") + "厨" + jsonObject1.getInt("hToilet") + "卫");
                                    if (jsonObject1.getString("hToilettype").equals("0")) {
                                        list.get(2).setCount("独立卫生间");
                                    } else {
                                        list.get(2).setCount("共用卫生间");
                                    }
                                    list.get(3).setCount(jsonObject1.getString("hPeoples") + "人");
                                    discountAdapter.notifyDataSetChanged();

                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

        }


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        area();
                        break;
                    case 1:
                        showPopupWindow_type();
                        break;
                    case 2:
                        showPopupWindow_wei();
                        break;
                    case 3:
                        showPopupWindow_person();
                        break;
                    case 4:
                        if (info.equals("post")) {
                            Intent intent = new Intent(BaseInfoActivity.this, SetBedActivity.class);
                            intent.putExtra("info", "post");
                            BaseInfoActivity.this.startActivityForResult(intent, 0x001);
                        } else {
//                            Log.e("bbbbbbbbb", bed_type);
//                            Log.e("bbbbbbbbb", bed_l + "");
//                            Log.e("bbbbbbbbb", bed_w + "");
//                            Log.e("bbbbbbbbb", bed_count);
                            Intent intent = new Intent(BaseInfoActivity.this, SetBedActivity.class);
//                            intent.putExtra("bed_type", bed_type);
//                            intent.putExtra("bed_l", bed_l + "");
//                            intent.putExtra("bed_w", bed_w + "");
//                            intent.putExtra("bed_count", bed_count);
                            intent.putExtra("info", "edit");
                            BaseInfoActivity.this.startActivityForResult(intent, 0x001);
                        }

                        break;

                }
            }
        });
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0x001 && data != null) {
//            if (resultCode == 0x002) {
//               MyApp.re_bedtype = data.getStringExtra("base_bed_type");
//                MyApp.re_bedl = data.getStringExtra("base_bed_l");
//                MyApp.re_bedw = data.getStringExtra("base_bed_w");
//                MyApp.re_bedcount = data.getStringExtra("base_bed_count");
//                Log.e("bbbbbbbbbb", data.getStringExtra("base_bed_type") + data.getStringExtra("base_bed_l") + data.getStringExtra("base_bed_w") + data.getStringExtra("base_bed_count"));
//            }
//        }
//
//    }

    public void showPopupWindow_wei() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_win_wei, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        TextView pop_friend_wx = (TextView) contentView.findViewById(R.id.pop_friend_wx);
        TextView pop_friend_wxc = (TextView) contentView.findViewById(R.id.pop_friend_wxc);
        TextView pop_off = (TextView) contentView.findViewById(R.id.pop_off);
        pop_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_friend_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                list.get(2).setCount("独立卫生间");
                discountAdapter.notifyDataSetChanged();
                MyApp.base_wei = "0";

            }
        });
        pop_friend_wxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                list.get(2).setCount("共用卫生间");
                discountAdapter.notifyDataSetChanged();
                MyApp.base_wei = "1";
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        if (popupWindow.isShowing()) {

        } else {
            popupWindow.showAsDropDown(contentView);
        }

    }

    private void showPopupWindow_type() {
        View contentView = null;
        //设置contentView
        contentView = LayoutInflater.from(this).inflate(R.layout.dialog_housetype_select, null);
        wv_shi = (WheelView) contentView.findViewById(R.id.wv_shi);
        wv_shi.setOffset(1);
        wv_shi.setItems(Arrays.asList(SHI));
        wv_ting = (WheelView) contentView.findViewById(R.id.wv_ting);
        wv_ting.setOffset(1);
        wv_ting.setItems(Arrays.asList(TING));
        wv_chu = (WheelView) contentView.findViewById(R.id.wv_chu);
        wv_chu.setOffset(1);
        wv_chu.setItems(Arrays.asList(CHU));
        wv_wei = (WheelView) contentView.findViewById(R.id.wv_wei);
        wv_wei.setOffset(1);
        wv_wei.setItems(Arrays.asList(WEI));
        affirm = (TextView) contentView.findViewById(R.id.queren);
        final PopupWindow mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        mPopWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        mPopWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        affirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ting = wv_ting.getSeletedItem();
                String shi = wv_shi.getSeletedItem();
                String chu = wv_chu.getSeletedItem();
                String wei = wv_wei.getSeletedItem();
//                String yang = wv_yang.getSeletedItem();
                mPopWindow.dismiss();
//                TextView textView = (TextView) lv.getChildAt(0).findViewById(R.id.count);
//                textView.setText(shi + ting + wei + chu + yang);
                list.get(1).setCount(shi + ting + chu + wei);
                discountAdapter.notifyDataSetChanged();
                MyApp.base_type_shi = shi.substring(0, 1);
                MyApp.base_type_ting = ting.substring(0, 1);
                MyApp.base_type_wei = wei.substring(0, 1);
                MyApp.base_type_chu = chu.substring(0, 1);
                MyApp.base_type = shi + ting + chu + wei;

            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);

            }
        });
    }

    private void area() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.dialog_price_set, null);
        final TextView baocun = (TextView) view.findViewById(R.id.baocun);
        final EditText price = (EditText) view.findViewById(R.id.price);
        builder.setView(view);
        final AlertDialog dialog = builder.show();
        baocun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                list.get(0).setCount(price.getText() + "平方");
                discountAdapter.notifyDataSetChanged();
                MyApp.base_area = price.getText() + "";
//                TextView textView = (TextView) lv.getChildAt(0).findViewById(R.id.count);
//                textView.setText(price.getText() + "平方");

            }
        });
    }

    private void showPopupWindow_person() {
        View contentView = null;
        //设置contentView
        contentView = LayoutInflater.from(this).inflate(R.layout.mywheelview, null);
        wva = (WheelView) contentView.findViewById(R.id.main_wv);
        affirm = (TextView) contentView.findViewById(R.id.queren);

        wva.setOffset(1);
        wva.setItems(Arrays.asList(PLANETS));

        wva.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.d("qqqqqqqq", "selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });


        final PopupWindow mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        mPopWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        mPopWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        affirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = wva.getSeletedItem();
                mPopWindow.dismiss();
                list.get(3).setCount(string);
                discountAdapter.notifyDataSetChanged();
                MyApp.base_person = string.replace("人", "");

            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);

            }
        });
    }


    @OnClick({R.id.back, R.id.baocun})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.baocun:
                Intent intent = new Intent();
                if (info.equals("post")) {
                    if (MyApp.base_area != null && MyApp.base_type != null && MyApp.base_wei != null && MyApp.base_person != null && MyApp.base_person != null && MyApp.base_bed_type != null && MyApp.base_bed_l != null && MyApp.base_bed_w != null && MyApp.base_bed_count != null) {
                        intent.putExtra("info", "完成");
                    } else {
                        intent.putExtra("info", "未完成");
                    }
                    intent.putExtra("date", MyApp.dis_date);
                    intent.putExtra("price", MyApp.dis_price);
                    intent.putExtra("dis_7", MyApp.dis_7);
                    intent.putExtra("dis_30", MyApp.dis_30);
                    setResult(0x005, intent);
                    finish();
                } else {
                    LoadingDialog.show(this);
                    TextView area = (TextView) lv.getChildAt(0).findViewById(R.id.count);
                    TextView type = (TextView) lv.getChildAt(1).findViewById(R.id.count);
                    TextView wei = (TextView) lv.getChildAt(2).findViewById(R.id.count);
                    TextView person = (TextView) lv.getChildAt(3).findViewById(R.id.count);
                    String wei_string = "";
                    if ((wei.getText() + "").equals("独立卫生间")) {
                        wei_string = "0";
                    } else {
                        wei_string = "1";
                    }
                    Log.e("bbbbbbbbbbbbbb","re="+SPUtils.get(this, "token", "") + "");
                    Log.e("bbbbbbbbbbbbbb","re="+id);
                    Log.e("bbbbbbbbbbbbbb","re="+(area.getText() + "").substring(0, (area.getText() + "").indexOf("平")));
                    Log.e("bbbbbbbbbbbbbb","re="+(type.getText() + ""));
                    Log.e("bbbbbbbbbbbbbb","re="+(type.getText() + "").substring(0, (type.getText() + "").indexOf("室")));
                    Log.e("bbbbbbbbbbbbbb","re="+(type.getText() + "").substring((type.getText() + "").indexOf("室") + 1, (type.getText() + "").indexOf("厅")));
                    Log.e("bbbbbbbbbbbbbb","re="+(type.getText() + "").substring((type.getText() + "").indexOf("厅") + 1, (type.getText() + "").indexOf("厨")));
                    Log.e("bbbbbbbbbbbbbb","re="+ (type.getText() + "").substring((type.getText() + "").indexOf("厨") + 1, (type.getText() + "").indexOf("卫")));
                    Log.e("bbbbbbbbbbbbbb","re="+wei_string);
                    Log.e("bbbbbbbbbbbbbb","re="+(person.getText() + "").substring(0, (person.getText() + "").indexOf("人")));
                    Log.e("bbbbbbbbbbbbbb","re="+ MyApp.re_bedtype);
                    Log.e("bbbbbbbbbbbbbb","re="+ MyApp.re_bedl);
                    Log.e("bbbbbbbbbbbbbb","re="+ MyApp.re_bedw);
                    Log.e("bbbbbbbbbbbbbb","re="+ MyApp.re_bedcount);

                    OkHttpUtils.get()
                            .addParams("token", SPUtils.get(this, "token", "") + "")
                            .addParams("id", id)
                            .addParams("hArea", (area.getText() + "").substring(0, (area.getText() + "").indexOf("平")))
                            .addParams("hRoom", (type.getText() + "").substring(0, (type.getText() + "").indexOf("室")))
                            .addParams("hHall", (type.getText() + "").substring((type.getText() + "").indexOf("室") + 1, (type.getText() + "").indexOf("厅")))
                            .addParams("hRooms", (type.getText() + "").substring((type.getText() + "").indexOf("厅") + 1, (type.getText() + "").indexOf("厨")))
                            .addParams("hToilet", (type.getText() + "").substring((type.getText() + "").indexOf("厨") + 1, (type.getText() + "").indexOf("卫")))
                            .addParams("hToilettype", wei_string)
                            .addParams("hPeoples", (person.getText() + "").substring(0, (person.getText() + "").indexOf("人")))
                            .addParams("hBedtype",  MyApp.re_bedtype)
                            .addParams("hBedlength",  MyApp.re_bedl)
                            .addParams("hBedwidth",  MyApp.re_bedw)
                            .addParams("hBednum",  MyApp.re_bedcount)
                            .url(API.BaseApi_L + API.UpdateHouseBaseInfo_Api)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    LoadingDialog.dismiss(BaseInfoActivity.this);
                                    T.showShort(BaseInfoActivity.this, "数据加载失败，请稍后再试");
                                }

                                @Override
                                public void onResponse(String response) {
                                    LoadingDialog.dismiss(BaseInfoActivity.this);
                                    Log.e("bbbbbbbbbbbbbb","re="+response);
                                    try {
                                        JSONObject jsonObject=new JSONObject(response);
                                        if (jsonObject.getInt("status")==0){
                                            T.showShort(BaseInfoActivity.this,jsonObject.getString("msg") + " 后台审核中...");
                                            finish();
                                        } else {
                                            T.showShort(BaseInfoActivity.this,jsonObject.getString("msg"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                }

                break;
        }
    }
}
